<template>
	<div class="sticky_fixed">
		<div
			class="sticky_fixed_inner"
			ref="stickyFixedRef"
			:class="`position_${position}`"
			:style="{background, zIndex, ...fixedStyle}"
		>
			<slot />
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, nextTick, defineProps, defineExpose } from 'vue'
import { observeDOM } from '@/utils'

const props = defineProps({
	position: {
		type: String,
		default: 'bottom',
	},
	background: {
		type: String,
		default: '#fff',
	},
	showShadow: {
		type: Boolean,
		default: false,
	},
	zIndex: {
		type: [Number, String],
		default: 99,
	},
	height: {
		type: [Number, String],
		default: 0,
	},
})

const fixedStyle = ref({ left: 0, top: 0, right: 0, bottom: 0 })
const parseFixedStyle = () => {
	if (props.position === 'none') {
		return
	}
	if (props.position === 'left') {
		Object.assign(fixedStyle.value, {
			position: 'fixed',
			right: 'auto',
			boxShadow: props.showShadow
				? `2px 0px 6px 0px rgba(102,102,102,0.06)`
				: '',
		})
		return
	}
	if (props.position === 'top') {
		Object.assign(fixedStyle.value, {
			position: 'fixed',
			bottom: 'auto',
			boxShadow: props.showShadow
				? `0px 2px 6px 0px rgba(102,102,102,0.06)`
				: '',
		})
		return
	}
	if (props.position === 'right') {
		Object.assign(fixedStyle.value, {
			position: 'fixed',
			left: 'auto',
			boxShadow: props.showShadow
				? `-2px 0px 6px 0px rgba(102,102,102,0.06)`
				: '',
		})
		return
	}
	Object.assign(fixedStyle.value, {
		position: 'fixed',
		top: 'auto',
		boxShadow: props.showShadow
			? `0px -2px 6px 0px rgba(102,102,102,0.06)`
			: '',
	})
}
parseFixedStyle()

const stickyFixedRef = ref(null)
const stickyBottomHeight = ref(0)
const refresh = async () => {
	await nextTick()
	if (stickyFixedRef.value) {
		stickyBottomHeight.value = `${stickyFixedRef.value.offsetHeight}px`
	}
}
onMounted(() => {
	observeDOM(stickyFixedRef.value, 'resize', refresh)
})
defineExpose({ refresh })
</script>

<style lang="less" scoped>
@import '~@CSS/share.less';
.sticky_fixed {
	height: v-bind(stickyBottomHeight);
	.sticky_fixed_inner {
		line-height: 0;
		&.position_bottom {
			.safe_padding_bottom();
		}
	}
}
</style>
